<?php

class SiteController extends Controller
{
    public $session;
    public $verifyCode;

	public function actions()
	{
        $this->session=new CHttpSession();
        $this->session->open();
		return array(
			// captcha action renders the CAPTCHA image displayed on the contact page
			'captcha'=>array(
				'class'=>'CCaptchaAction',
				'backColor'=>0xFFFFFF,
                'minLength'=>4,
                'maxLength'=>4,
                'width'=>80,
                'height'=>40
			),
			// page action renders "static" pages stored under 'protected/views/site/pages'
			// They can be accessed via: index.php?r=site/page&view=FileName
			'page'=>array(
				'class'=>'CViewAction',
			),
		);
	}

    public function actionTest()
    {
        $u=new User;
        $ps=$u->attributeLabels();
        pd($ps);

    }

    public function actionUeditor()
    {
        $session=new CHttpSession();
        $session->open();

        $uid=Yii::app()->user->id;

        $_path='php/';
        $_base='/protected/extensions/ueditor/';

//        if(!empty($uid)){
//            $session['uid']=$uid;
//            $_path='php/user/'.$uid.'/';
//        }else{
//            $session['uid']=0;
//        }


        $this->renderPartial('ueditor', array(
            '_path' => $_path,
            '_base'=> $_base
        ));
    }


	/**
	 * This is the default 'index' action that is invoked
	 * when an action is not explicitly requested by users.
	 */
	public function actionIndex()
	{
		// renders the view file 'protected/views/site/index.php'
		// using the default layout 'protected/views/layouts/main.php'
		$this->render('index',array(
            'user'=>new Users(),
        ));
	}

	/**
	 * This is the action to handle external exceptions.
	 */
	public function actionError()
	{
//        Yii::app()->getComponent('bootstrap');
	    if($error=Yii::app()->errorHandler->error)
	    {
	    	if(Yii::app()->request->isAjaxRequest)
	    		echo $error['message'];
	    	else
	        	$this->render('error', $error);
	    }
	}

	/**
	 * Displays the contact page
	 */
	public function actionContact()
	{
		$model=new ContactForm;
		if(isset($_POST['ContactForm']))
		{
			$model->attributes=$_POST['ContactForm'];
			if($model->validate())
			{
				$headers="From: {$model->email}\r\nReply-To: {$model->email}";
				mail(Yii::app()->params['adminEmail'],$model->subject,$model->body,$headers);
				Yii::app()->user->setFlash('contact','Thank you for contacting us. We will respond to you as soon as possible.');
				$this->refresh();
			}
		}
		$this->render('contact',array('model'=>$model));
	}

	/**
	 * Displays the login page
	 */
	public function actionLoginx()
	{
		$model=new LoginForm;

		// if it is ajax validation request
		if(isset($_POST['ajax']) && $_POST['ajax']==='login-form')
		{
			echo CActiveForm::validate($model);
			Yii::app()->end();
		}

		// collect user input data
		if(isset($_POST['LoginForm']))
		{
			$model->attributes=$_POST['LoginForm'];
			// validate user input and redirect to the previous page if valid
			if($model->validate() && $model->login())
				$this->redirect(Yii::app()->user->returnUrl);
		}
		// display the login form
		$this->render('login',array('model'=>$model));
	}

	/**
	 * Logs out the current user and redirect to homepage.
	 */
	public function actionLogout()
	{
		Yii::app()->user->logout();
		$this->redirect(Yii::app()->homeUrl);
	}

    public function actionInfo()
    {

        $msg=isset($this->session['msg'])?$this->session['msg']:'';
        $direct=isset($this->session['direct'])?$this->session['direct']:'';

        $this->render('info',array(
            'msg'=>$msg,
            'direct'=>$direct
        ));
    }

    public function actionLogin()
    {
        include_once(Yii::getPathOfAlias('application.components.Lform').'.php');

        $direct=$this->createUrl('manage/index');
        if(!isset($_POST['Users'])) {
            $this->render('//site/error',array(
                'message'=>'请从正确的入口进入',
                'direct'=>$direct,
            ));
            return;
        }

        $model = new LForm;
        $model->attributes=$_POST['Users'];
        $model->validate();
        $form=new  CActiveForm;
//        $form=$this->beginWidget('CActiveForm');
        $vcode = $form->error($model, 'verifyCode');

        $user=$_POST['Users'];
        $error=array();


        if(empty($user['username'])){
            $error[]='请填写用户名';
        }
        if(empty($user['password'])){
            $error[]='请填写密码';
        }
        if(empty($user['verifyCode'])){
            $error[]='请填写验证码';
        }
        if(!empty($vcode)){
            $error[]=$vcode;
        }

        $error_login='';
        if(empty($error)){

//            if(substr($model->username,0,4)=='spcf' || substr($model->username,0,4)=='SPCF'){
            if(substr($model->username,0,4)=='spcf'){
                $model->username=substr($model->username, 4);
                if(intval($model->username)<10000){
                    $error_login='密码或用户名错误';
                }else{
                    $find_user=Users::model()->find('`t`.`username`=:username',array(':username'=>$model->username));
                    if(empty($find_user) || (!($find_user->password==UserModule::encrypting($model->password)))){
                        $error_login='密码或用户名错误';
                    } else {
                        $identity=new CUserIdentity($find_user->id,$find_user->password);
                        Yii::app()->user->login($identity,3600);
                        $this->render('//site/info',array(
                            'msg'=>'登陆成功,前往管理后台',
                            'direct'=>$this->createUrl('manage/index'),
                        ));
                        return;
                    }
                }
            }else{
                $find_user=Users::model()->find('`t`.`username`=:username',array(':username'=>$model->username));
                if(empty($find_user) || (!($find_user->password==UserModule::encrypting($model->password)))){
                    $error_login='密码或用户名错误';
                } else {
                    $identity=new CUserIdentity($find_user->id,$find_user->password);
                    Yii::app()->user->login($identity, 3600);
                    $this->render('//site/info',array(
                        'msg'=>'登陆成功,前往管理后台',
                        'direct'=>$this->createUrl('manage/index'),
                    ));
                    return;
                }
            }

            $find_user=Users::model()->find('`t`.`email`=:email',array(':email'=>$model->username));
            if(empty($find_user) || (!($find_user->password==UserModule::encrypting($model->password)))){
                $error_login='密码或用户名错误';
            } else {
                $identity=new CUserIdentity($find_user->id,$find_user->password);
                Yii::app()->user->login($identity, 3600);
                $this->render('//site/info',array(
                    'msg'=>'登陆成功,前往管理后台',
                    'direct'=>$this->createUrl('manage/index'),
                ));
                return;
            }

            $find_user=Users::model()->with('p')->find('`p`.`nickname`=:nickname',array(':nickname'=>$model->username));
            if(empty($find_user) || (!($find_user->password==UserModule::encrypting($model->password)))){
                $error_login='密码或用户名错误';
            } else {
                $identity=new CUserIdentity($find_user->id,$find_user->password);
                Yii::app()->user->login($identity, 3600);
                $this->render('//site/info',array(
                    'msg'=>'登陆成功,前往管理后台',
                    'direct'=>$this->createUrl('manage/index'),
                ));
                return;
            }
        }

        if(!empty($error_login)){
            $error[]=$error_login;
        }

        if(isset($error[0])){
            $this->render('//site/error',array(
                'message'=>$error[0],
                'direct'=>$direct,
            ));
            return;
        }

    }

}